package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql" //注册驱动器
	"log"
	"xorm.io/xorm"
)

func connectMySQL() *xorm.Engine {
	//数据库连接基本信息
	var (
		userName  = "root"
		password  = "Wl123456"
		ipAddress = "10.0.210.157"
		port      = 3306
		dbName    = "go_xorm"
		charset   = "utf8mb4"
	)
	//构建数据库连接信息
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddress, port, dbName, charset)

	engine, err := xorm.NewEngine("mysql", dataSourceName)
	if err != nil {
		log.Fatal("数据库连接失败")
	}
	//同步 struct 和 数据库结构
	err = engine.Sync(new(User))
	if err != nil {
		log.Fatal("表结构同步失败")
	}
	return engine
}
